<!--
 * @Author: 冯本桥
 * @Date: 2025-02-15 18:40:06
 * @LastEditTime: 2025-03-28 20:24:46
 * @LastEditors: 冯本桥
 * @Description: 教师档案
 * @FilePath: \teach_system_fe\src\views\teacherManagement\teacherFile.vue
-->
<template>
  <div v-loading="loading">
    <div class="header-search cad-box">
      <el-input
        v-model="searchValue.realName"
        style="width: 20%"
        clearable
        placeholder="请输入教师姓名"
      />
      <el-select
        v-model="searchValue.status"
        class="select-box"
        clearable
        placeholder="请选择"
      >
        <el-option
          v-for="(item, index) in config.stateDate"
          :key="index"
          :label="item.label"
          :value="item.value"
        />
      </el-select>

      <el-button type="primary" @click="onSubmit">确定</el-button>
    </div>

    <div class="content-table cad-box">
      <el-button
        style="margin-bottom: 20px"
        type="primary"
        @click="addTeacher"
      >添加教师</el-button>

      <el-table
        :data="tableData"
        style="width: 100%; margin: 30px 0"
        :header-cell-style="{
          backgroundColor: '#fafafc',
          color: '#000000',
        }"
      >
        <el-table-column
          v-for="(item, index) in config.teacherFileTable"
          :key="index"
          :prop="item.key"
          :label="item.name"
          show-overflow-tooltip
          align="center"
        >
          <template slot-scope="scope">
            <span v-if="item.slot">
              {{ tableSlotValue(sexList, scope.row[item.key]) }}
            </span>

            <span v-else>
              <span
                v-if="item.state"
                style="
                  display: flex;
                  align-items: center;
                  justify-content: center;
                "
              >
                <div
                  v-if="scope.row[item.key]"
                  :style="{
                    backgroundColor:
                      scope.row[item.key] === '在职' ? '#7fc53d' : '#7a798b',
                  }"
                  class="state-box"
                />
                <span>{{ scope.row[item.key] || "-" }}</span>
              </span>
              <span v-else>{{ scope.row[item.key] || "-" }}</span>
            </span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作">
          <template slot-scope="scope">
            <el-button
              style="color: #67c23a"
              type="text"
              size="small"
              @click="info(scope.row.id)"
            >
              详情
            </el-button>
            <el-button type="text" size="small" @click="edit(scope.row.id)">
              编辑
            </el-button>
            <el-button
              v-if="scope.row.status"
              style="color: #909399"
              type="text"
              size="small"
              @click="entry(scope.row.id)"
            >
              入职
            </el-button>
            <el-button
              v-else
              style="color: #909399"
              type="text"
              size="small"
              @click="dimission(scope.row.id)"
            >
              离职
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="text-align: right">
        <el-pagination
          :current-page="pagination.pageNum"
          :page-sizes="[10, 15, 30, 50]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <el-drawer
      title="教师详情"
      :visible.sync="drawerInfo"
      :before-close="beforeClose"
      :destroy-on-close="true"
      custom-class="add-drawer"
      :wrapper-closable="false"
      size="40%"
    >
      <div style="padding: 0 30px">
        <div class="title-box">基本信息</div>
        <from-page
          ref="infoFromRef"
          :disabled-from="true"
          :label-width="null"
          :rules="{}"
          :but-show="false"
          :from-config="infoTeacher"
          :grid-data="gridData"
        />

        <div>
          <div class="img-title">个人照片</div>
          <div v-if="infoDate.workFormPhoto || ''">
            <el-image
              style="
                border-radius: 5px;
                width: 150px;
                height: 150px;
                cursor: pointer;
              "
              :src="infoDate.workFormPhoto"
              :preview-src-list="[infoDate.workFormPhoto]"
              fit="fit"
            />
          </div>
          <div class="img-title title-box">教育履历</div>
          <div
            v-if="ifLength(infoDate.staffChildPOList1)"
            class="border-box-item"
          >
            <div
              v-for="(item, index) in infoDate.staffChildPOList1"
              :key="index"
              class="message-box"
            >
              <div style="width: 30%">
                毕业院校：<span>{{ item.almaMater }}</span>
              </div>
              <div style="flex: 1">
                学历层次：<span>{{ item.educationalLevel }}</span>
              </div>
              <div style="width: 30%">
                所学专业：<span>{{ item.major }}</span>
              </div>
            </div>
            <div>
              <div style="margin-bottom: 20px">证书信息：</div>
              <div class="img-box">
                <el-image
                  v-for="(item, index) in imgSet(infoDate.certificate)"
                  :key="index"
                  style="border-radius: 5px; height: 50px; cursor: pointer"
                  :src="item.url"
                  :preview-src-list="[item.url]"
                  fit="fit"
                />
              </div>
            </div>
          </div>
          <div
            v-if="ifLength(infoDate.staffChildPOList2)"
            class="border-box-item"
          >
            <div
              v-for="(item, index) in infoDate.staffChildPOList2"
              :key="index"
              class="message-box"
            >
              <div style="width: 33%">
                从业证书：<span>{{
                  tableSlotValue(config.certificate, item.workingCertificate)
                }}</span>
              </div>
              <div style="width: 33%">
                获证时间：<span>{{ item.certificationTime }}</span>
              </div>
              <div style="width: 33%">
                过期时间：<span>{{ item.expirationTime }}</span>
              </div>
              <div style="margin-top: 20px">
                <div style="margin-bottom: 20px">证书信息：</div>
                <div class="img-box">
                  <el-image
                    v-for="(item, index) in imgSet(item.certificateEmployment)"
                    :key="index"
                    style="border-radius: 5px; height: 50px; cursor: pointer"
                    :src="item.url"
                    fit="fit"
                    :preview-src-list="[item.url]"
                  />
                </div>
              </div>
            </div>
            <!-- <div>
              <div style="margin-bottom: 20px">证书信息：</div>
              <div class="img-box">
                <el-image
                  v-for="(item, index) in imgSet(
                    infoDate.certificateEmployment
                  )"
                  :key="index"
                  style="border-radius: 5px; height: 50px; cursor: pointer"
                  :src="item.url"
                  fit="fit"
                  :preview-src-list="[item.url]"
                />
              </div>
            </div> -->
          </div>

          <div class="img-title title-box">工作履历</div>
          <div
            v-if="ifLength(infoDate.staffChildPOList3)"
            class="border-box-item"
          >
            <div
              v-for="(item, index) in infoDate.staffChildPOList3"
              :key="index"
              class="message-box"
              style="margin-bottom: 0"
            >
              <div style="width: 30%">
                工作单位：<span>{{ item.almaMater }}</span>
              </div>
              <div style="flex: 1">
                起止时间：<span>{{
                  item.startStopTime
                    ? `${item.startStopTime[0] || "-"} - ${
                      item.startStopTime[1] || "-"
                    }`
                    : ""
                }}</span>
              </div>
              <div style="width: 30%">
                任职岗位：<span>{{ item.major }}</span>
              </div>
            </div>
          </div>
          <div class="img-title title-box">任职信息</div>
          <div
            v-if="ifLength(infoDate.staffChildPOList4)"
            class="border-box-item"
          >
            <div
              v-for="(item, index) in infoDate.staffChildPOList4"
              :key="index"
              class="message-box"
            >
              <div style="width: 30%">
                所属班级：<span>{{
                  tableValueValue(classesOption, item.classesId, "id").name ||
                    "-"
                }}</span>
              </div>

              <div style="flex: 1">
                担任岗位：<span>{{
                  tableValueValue(
                    positionHeldOption,
                    item.positionHeld,
                    "roleId"
                  ).roleName || "-"
                }}</span>
              </div>
            </div>
            <div style="display: flex">
              <div style="width: 100px">附件信息：</div>
              <div style="display: flex; flex-direction: column">
                <el-link
                  v-for="(item, index) in imgSet(infoDate.file)"
                  :key="index"
                  style="margin-bottom: 20px"
                  type="primary"
                  @click="openPage(item.url)"
                >{{ item.url }}</el-link>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import * as config from './config'
import {
  submitTeacher,
  staffQuit,
  staffEntry,
  getDetailById
} from './api/teacher'
import { getRoleTypes, getList } from './api/index'
import FromPage from '@/components/Basic/FromPage/index'
export default {
  components: {
    FromPage
  },
  data () {
    return {
      config: config,
      loading: false,
      searchValue: {
        realName: '',
        status: ''
      },
      gridData: {
        columns: 2, // 默认列数
        rows: 1, // 默认行数
        rowsWidth: '75px',
        columnsNumber: '6px',
        rowsNumber: '62px'
      },
      drawerInfo: false,
      tableData: [],
      positionHeldOption: [],
      classesOption: [],
      pagination: {
        pageNum: 0,
        pageSize: 10
      },
      total: 0,
      infoDate: {},
      infoTeacher: config.addTeacher.slice(0, config.addTeacher.length - 1),
      sexList: this.$store.getters.dict.sex
    }
  },
  computed: {
    ...mapGetters(['curArea']),
    tableSlotValue () {
      return (data, value) => {
        return data.find((item) => item.value * 1 === value * 1)?.label || ''
      }
    },

    ifLength () {
      return (value) => {
        return !!value?.length
      }
    },

    tableValueValue () {
      return (data, value, key) => {
        return data.find((item) => item[key] === value) || ''
      }
    },

    imgSet () {
      return (value) => {
        const urlArray = value?.split(',').filter((url) => url.trim() !== '')
        return urlArray?.map((url) => ({ url: url.trim() }))
      }
    }
  },
  created () {
    this.getUser()
    this.getRole()
    this.getTableList()
  },
  mounted () {},
  methods: {
    openPage (url) {
      window.open(url)
    },

    async getInfoList (id) {
      try {
        const res = await getDetailById({ staffId: id })
        this.infoDate = res
        this.$nextTick(() => {
          this.$refs.infoFromRef.formDate = res
          this.$refs.infoFromRef.formDate.gender = String(res.gender)
          this.$refs.infoFromRef.formDate.idCard = res?.idCard
            ? res.idCard?.slice(0, 12) + '******'
            : ''
        })
      } catch (error) {
        console.log(error)
      }
    },

    async getRole () {
      try {
        const res = await getRoleTypes()
        this.positionHeldOption = res
      } catch (error) {
        console.log(error)
      }
    },

    async getUser () {
      try {
        const res = await getList({
          areaId: this.curArea.areaId || '',
          pageNum: 0,
          pageSize: 10
        })
        this.classesOption = res.content
      } catch (error) {
        console.log(error)
      }
    },

    onSubmit () {
      this.getTableList()
    },

    addTeacher () {
      this.$router.push({ path: '/teacherManagement/addTeacher' })
      console.log('添加教师')
    },

    info (id) {
      console.log('详情')
      this.drawerInfo = true
      this.getInfoList(id)
    },

    edit (id) {
      console.log('编辑')
      this.$router.push({
        path: `/teacherManagement/addTeacher?types=edit&id=${id}`
      })
    },

    beforeClose () {
      try {
        this.$refs.infoFromRef.resetFields()
        this.$refs.infoFromRef.formDate = {}
      } catch (error) {
        console.log(error)
      }
      this.infoDate = {}
      this.drawerInfo = false
    },

    async getTableList () {
      this.loading = true
      try {
        const siz = JSON.parse(JSON.stringify(this.pagination.pageNum))
        const res = await submitTeacher({
          areaId: this.curArea.areaId,
          deleted: false,
          ...this.pagination,
          ...this.searchValue,
          pageNum: siz ? siz - 1 : siz
        })
        this.tableData = res.content
        this.total = res.totalElements
      } catch (error) {
        console.log(error)
      } finally {
        this.loading = false
      }
    },

    dimission (id) {
      console.log('离职')
      this.$confirm('是否确认离职?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.setStaffQuit(id)
        })
        .catch(() => {})
    },

    async setStaffQuit (id) {
      this.loading = true
      try {
        await staffQuit({ staffId: id })
        this.$message({
          type: 'success',
          message: '离职成功!'
        })
        this.getTableList()
      } catch (error) {
        console.log(error)
      } finally {
        this.loading = false
      }
    },

    entry (id) {
      this.$confirm('是否确认入职?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.setStaffEntry(id)
        })
        .catch(() => {})
    },

    async setStaffEntry (id) {
      this.loading = true
      try {
        await staffEntry({ staffId: id })
        this.$message({
          type: 'success',
          message: '入职成功!'
        })
        this.getTableList()
      } catch (error) {
        console.log(error)
      } finally {
        this.loading = false
      }
    },

    handleSizeChange (val) {
      console.log(`每页 ${val} 条`)
      this.pagination.pageSize = val
      this.getTableList()
    },

    handleCurrentChange (val) {
      console.log(`当前页: ${val}`)
      this.pagination.pageNum = val
      this.getTableList()
    }
  }
}
</script>

<style scoped lang="scss">
.header-search {
  display: flex;
  margin-bottom: 30px;

  .select-box {
    width: 20%;
    margin: 0 20px;
  }
}

.content-table {
  .state-box {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    margin-right: 10px;
  }
}

.img-title {
  font-size: 15px;
  font-weight: bold;
  margin: 20px 0;
}
.img-box {
  display: grid;
  grid-template-columns: repeat(
    auto-fill,
    minmax(50px, 1fr)
  ); /* 自适应列数，每列最小宽度150px */
  grid-gap: 20px; /* 设置每个图片之间的间距 */
}

.title-box {
  margin-bottom: 30px;
  font-weight: bold;
  font-size: 20px;
}

.border-box-item {
  border: 1px solid #eeeef0;
  border-radius: 5px;
  background-color: #fafafc;
  padding: 20px 20px;
  margin-bottom: 20px;
  color: black;
  span {
    color: #b0b0b2;
    font-size: 15px;
  }

  .message-box {
    display: flex;
    margin-bottom: 20px;
    flex-wrap: wrap;
  }
}
</style>
